import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttercommon/src/http/file_upload.dart';
import 'package:fluttercommon/src/widgets/cupertino_loading_widget.dart';
import 'package:photo_view/photo_view.dart';

class PhotoPreviewPage extends StatelessWidget {
  final FileUploadBean photo;
  final String? heroTag;

  const PhotoPreviewPage({
    Key? key,
    required this.photo,
    this.heroTag,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Stack(
        children: <Widget>[
          PhotoView(
            loadingBuilder: (context, progress) => CupertinoLoadingWidget(),
            backgroundDecoration: BoxDecoration(color: Colors.transparent),
            imageProvider: (photo.hasLocalCache
                ? FileImage(File(photo.localPath!))
                : NetworkImage(photo.url!)) as ImageProvider<Object>?,
          ),
          Align(
              alignment: Alignment.bottomCenter,
              child: Padding(
                padding: const EdgeInsets.only(bottom: 24.0),
                child: CircleAvatar(
                  radius: 24.0,
                  child: IconButton(
                    icon: Icon(
                      Icons.close,
                      color: Colors.white,
                    ),
                    onPressed: () {
                      Navigator.maybePop(context, photo);
                    },
                  ),
                  backgroundColor: Theme.of(context).primaryColor,
                ),
              )),
        ],
      ),
    );
  }
}

class PreviewPhotosPage extends StatefulWidget {
  final List<String> photos;
  final String initial;
  final bool editable;

  const PreviewPhotosPage({
    Key? key,
    required this.photos,
    required this.initial,
    this.editable = true,
  }) : super(key: key);

  @override
  _PreviewPhotosPageState createState() => _PreviewPhotosPageState();
}

class _PreviewPhotosPageState extends State<PreviewPhotosPage>
    with TickerProviderStateMixin {
  late String current;
  late TabController tabController;
  late List<String> allPhotos;
  late ValueNotifier<String> titleNotifier;

  String getTitleString() {
    return "${allPhotos.indexOf(current) + 1}/${allPhotos.length}";
  }

  @override
  void initState() {
    current = widget.initial;
    allPhotos = List.from(widget.photos);
    tabController = TabController(
      length: allPhotos.length,
      vsync: this,
      initialIndex: allPhotos.indexOf(current),
    );
    titleNotifier = ValueNotifier(getTitleString());
    tabController.addListener(() {
      current = allPhotos[tabController.index];
      titleNotifier.value = getTitleString();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.of(context).pop(allPhotos);
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          title: ValueListenableBuilder<String>(
            valueListenable: titleNotifier,
            builder: (context, value, child) => Text(value),
          ),
          actions: [
            if (widget.editable)
              IconButton(
                onPressed: deleteCurrentImage,
                icon: Icon(Icons.delete_outline),
              )
          ],
        ),
        body: TabBarView(
          children: [
            for (final path in allPhotos)
              if (path.startsWith("http"))
                PhotoView(
                    loadingBuilder: (context, progress) =>
                        CupertinoLoadingWidget(),
                    backgroundDecoration:
                        BoxDecoration(color: Colors.transparent),
                    imageProvider: NetworkImage(path))
              else
                PhotoView(
                  loadingBuilder: (context, progress) =>
                      CupertinoLoadingWidget(),
                  backgroundDecoration:
                      BoxDecoration(color: Colors.transparent),
                  imageProvider: FileImage(File(path)),
                ),
          ],
          controller: tabController,
        ),
      ),
    );
  }

  void deleteCurrentImage() {
    int at = allPhotos.indexOf(current);
    int newIndex = at == allPhotos.length - 1 ? at - 1 : at;
    if (allPhotos.length == 1) {
      Navigator.of(context).pop(null);
    } else {
      allPhotos.remove(current);
      current = allPhotos[newIndex];
      tabController.dispose();
      titleNotifier.value = getTitleString();
      setState(() {
        tabController = TabController(length: allPhotos.length, vsync: this);
      });
    }
  }
}
